package com.imay.live.fragment.room;

import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.imay.base.fragment.BaseDialogFragment;
import com.imay.live.adapter.LinkMicUserAdapter;
import com.imay.live.helper.ThreadManager;
import com.imay.live.proto.ErrorResult;
import com.imay.live.proto.MessageId;
import com.imay.live.proto.ProtoResult;
import com.imay.live.proto.ResultCode;
import com.imay.live.proto.helper.ProtoCallBack;
import com.imay.live.proto.helper.ProtoRequestHelper;
import com.imay.live.proto.helper.ProtoSocketFactory;
import com.imay.live.proto.room.RoomLinkApplyListResp;
import com.imay.live.proto.user.UserInfoCard;
import com.imay.live.view.recyclerview.WrapContentLinearLayoutManager;
import com.imay.live.R;
import com.imay.tbas_api.IMYTBASObject;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;
import com.yqritc.recyclerviewflexibledivider.VerticalDividerItemDecoration;

import java.util.List;

/**
 * Created by jeaman on 2017/5/3.
 * 连麦列表
 */

public class LinkMicInviteFragment extends BaseDialogFragment implements View.OnClickListener {
    protected final static String BUNDLE_NAME_ROOM_ID = "roomId";

    protected RecyclerView mRecyclerView;
    protected TextView mNumberTv;
    protected Button mLinkBtn;
    protected View mContentView;
    protected View mEmptyView;

    protected LinkMicUserAdapter mAdapter;

    private IMYTBASObject mSocketNotify;
    protected long mRoomId;

    public static LinkMicInviteFragment newInstance(long roomId) {
        Bundle bundle = new Bundle();
        bundle.putLong(BUNDLE_NAME_ROOM_ID, roomId);
        LinkMicInviteFragment fragment = new LinkMicInviteFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_link_line;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        mContentView = $(R.id.link_line_ll_content);
        mEmptyView = $(R.id.link_line_ll_empty);
        mNumberTv = $(R.id.link_line_tv_number);
        mLinkBtn = $(R.id.link_line_btn_link);

        mRecyclerView = $(R.id.link_line_rv_user);

        mRecyclerView.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                boolean checked = mAdapter.toggleCheckUser(position);
                mLinkBtn.setEnabled(checked);   //没有选择用户，禁用按钮
            }
        });
        initData();
    }

    protected void initData() {
        mRoomId = getArguments().getLong(BUNDLE_NAME_ROOM_ID);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(new WrapContentLinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL));
        mRecyclerView.addItemDecoration(new VerticalDividerItemDecoration.Builder(getActivity()).sizeResId(R.dimen.divider_size_link_mic).color(Color.TRANSPARENT).build());

        mAdapter = new LinkMicUserAdapter(null);
        mRecyclerView.setAdapter(mAdapter);
        mLinkBtn.setOnClickListener(this);
        requestUserList();
        registerSocketNotify();
    }

    @Override
    protected int getGravity() {
        return Gravity.BOTTOM;
    }

    @Override
    protected boolean isMatchParent() {
        return true;
    }

    @Override
    protected int getHeight() {
        return WindowManager.LayoutParams.WRAP_CONTENT;
    };

    @Override
    protected boolean isOutsideTouchable() {
        return true;
    }

    @Override
    protected int getWindowAnimations() {
        return R.style.dialog_from_bottom;
    }

    protected void requestUserList() {
        ProtoRequestHelper.task(ProtoSocketFactory.requestLinkMicUser(mRoomId)).setTag(this.hashCode()).request(new ProtoCallBack() {
            @Override
            public void onRequestSuccess(String command, String data) {
                if (isAdded() && !isDetached()) {
                    RoomLinkApplyListResp resp = JSON.parseObject(data, RoomLinkApplyListResp.class);
                    if (resp.result == ResultCode.CodeSuccess) {
                        setUserList(resp.users);
                        setMeLinking(resp.meLinking);
                    } else {
                        ErrorResult.toastError(getActivity(), resp.result);
                    }
                }
            }

            @Override
            public void onRequestError(String command, int code, String message) {
                if (isAdded() && !isDetached()) {
                    ErrorResult.toastError(getActivity(), code);
                }
            }
        });
    }

    protected void setMeLinking(boolean meLinking) {
    }

    protected void registerSocketNotify() {
        mSocketNotify = new IMYTBASObject(false);
        mSocketNotify.stringCommand = "SOCK_NOTIFY";
        mSocketNotify.setDataResultListener(new IMYTBASObject.OnDataResultListener() {
            @Override
            public void onCommandTaskSuccess(final IMYTBASObject object) {
                if (object.socket_msg_id == MessageId.roomLinkApplyNotify) {
                    final RoomLinkApplyListResp resp = JSON.parseObject(object.socket_content, RoomLinkApplyListResp.class);
                    ThreadManager.post(new Runnable() {
                        @Override
                        public void run() {
                            if (mRoomId == resp.roomId) {
                                if (isAdded() && !isDetached()) {
                                    setUserList(resp.users);
                                }
                            }
                        }
                    });
                }
            }
        });
        mSocketNotify.addEventListenWithTBASObject();
    }

    protected void setUserList(List<UserInfoCard> userList) {
        if (userList == null || userList.size() == 0) {
            mContentView.setVisibility(View.GONE);
            mEmptyView.setVisibility(View.VISIBLE);
        } else {
            mContentView.setVisibility(View.VISIBLE);
            mEmptyView.setVisibility(View.GONE);
            mNumberTv.setText(getString(R.string.link_line_number, userList.size()));
        }
        mAdapter.setNewData(userList);
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        ProtoRequestHelper.cancelRequest(this.hashCode());
        mSocketNotify.destroy();
        super.onDismiss(dialog);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.link_line_btn_link:
                requestLinkMicInvite(mAdapter.getCheckedUser());
                break;
        }
    }

    private void requestLinkMicInvite(UserInfoCard user) {
        ProtoRequestHelper.task(ProtoSocketFactory.requestLinkMicInvite(user.uid)).setTag(this.hashCode()).request(new ProtoCallBack() {
            @Override
            public void onRequestSuccess(String command, String data) {
                dismiss();
            }

            @Override
            public void onRequestError(String command, int code, String message) {

            }
        });
    }
}
